package cn.melon.mod.login;

import org.json.JSONException;
import org.json.JSONObject;

import cn.melon.base.BaseController;
import cn.melon.mod.dorm.DormInfo;
import cn.melon.mod.dorm.dao.DormDaolmpl;
import cn.melon.mod.dorm.dao.IDormDao;
import cn.melon.mod.library.ILibraryBooksDao;
import cn.melon.mod.library.LibraryBooksDaoImpl;

public class LoginControler extends BaseController{

    private UserInfo info;
    public LoginControler(String request) {
        super(request);
    }

    @Override
    public void onResponse() {
        getUserInfo();
        JSONObject jsonRes = new JSONObject();
        ILibraryBooksDao booksDao = new LibraryBooksDaoImpl();
        IDormDao dormDao = new DormDaolmpl();
        
        
        if (info != null) {
            JSONObject jsonContent = new JSONObject();
            try {
                jsonContent.put("uuid", info.getUUID());
                jsonContent.put("type", info.getType());
                if (info.getType().equals("student")) {
                    int curLent =  booksDao.getBorrowCount(info.getStudentNum());
                    DormInfo dormInfo = dormDao.getDormInfo(info.getStudentNum());
            
                    jsonContent.put("cur_lent", curLent);
                    jsonContent.put("dorm_we", dormInfo.getWaterAndEletricityCharge());
                    jsonContent.put("card_left", "69.5");
                    jsonContent.put("course_need", 3);
                    jsonContent.put("exercise", 5);
                }
               
                jsonRes.put("content", jsonContent);
                jsonRes.put("code", 200);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        } else {
            try {
                jsonRes.put("content", "用户名或密码输入错误");
                jsonRes.put("code", 300);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        setResponse(jsonRes.toString());
    }
    

    public UserInfo getUserInfo() {
        IUserDao userDao = new IUserDaoImpl();
        if (info != null) {
            return info;
        }
        info = null;
        try {
            JSONObject jsonReq = new JSONObject(getRequest());
            info = userDao.
                    getUser(jsonReq.getString("student_num"), jsonReq.getString("password"));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        
        return info;
    }
}